<?php
require_once("lib/sqlConnector.php");

function getUserId($openidurl) {
	$resource = sqlQuery("SELECT userid FROM openid WHERE openidurl = '%s'", $openidurl);
    if ($resource && mysql_num_rows($resource) > 0) {
        $row = mysql_fetch_row($resource);
        return $row[0];  
    }
    return FALSE;
}
 
//TODO are these if statements necessary or does sql return false if not found?
function getOpenIDsByUser($userid) {
    $resource = sqlQuery("SELECT openidurl FROM openid WHERE userid = '%s'",$userid);
    if ($resource && mysql_num_rows($resource) > 0) {
        return multirow2Array($resource);
    }
    return FALSE;
}

//returns true if attached, false if already attached to something
function attachOpenID($openidurl, $userid) {
    return sqlQuery("INSERT INTO openid VALUES ('%s','%s')", array($openidurl,$userid,));
}
    
function detachOpenID($openidurl, $userid) {
    return sqlQuery("DELETE FROM openid WHERE openidurl = '%s' and userid = '%s'",array($openidurl,$userid));  
}
function detachOpenIDsByUser($userid) {
    return sqlQuery("DELETE FROM openid WHERE userid = '%s'",$userid);  
}

    
function newUser($openidurl, $mail, $username="") {
    if (strlen($username)==0) {
        $temp= explode("@",$mail,2);
        $username = $temp[0];
        unset($temp);
    }
    if (name2Id($username)) {//checking if the username is already in use
        $username = $mail;
    }
    $userid = sqlQuery("INSERT INTO users SET mail='%s',username='%s'", array($mail,$username),TRUE);
    attachOpenID($openidurl,$userid);  
    return $userid; 
}

function registerOpenId($openid) {
	$temp = $openid->getAttributes();  	    
	return newUser($openid->identity, $temp['contact/email']);
}
?>